from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
import json
from urllib.parse import urlparse, parse_qs
import os
from pathlib import Path
import time
import traceback

class CustomRequestHandler(BaseHTTPRequestHandler):
    # 禁用日志输出（可选）
    def log_message(self, format, *args):
        return
    
    # 设置响应头
    def _set_response(self, content_type="text/html; charset=utf-8", status=200):
        self.send_response(status)
        self.send_header("Content-Type", content_type)
        self.end_headers()
    
    # 获取文件的 MIME 类型
    def _get_mime_type(self, path):
        ext = os.path.splitext(path)[1].lower()
        mime_types = {
            '.html': 'text/html',
            '.css': 'text/css',
            '.js': 'application/javascript',
            '.json': 'application/json',
            '.png': 'image/png',
            '.jpg': 'image/jpeg',
            '.gif': 'image/gif',
            '.ico': 'image/x-icon',
            '.svg': 'image/svg+xml',
            '.txt': 'text/plain'
        }
        return mime_types.get(ext, 'application/octet-stream')
    
    # 处理 GET 请求
    def do_GET(self):
        # 解析 URL
        parsed_url = urlparse(self.path)
        path = parsed_url.path
        
        # API 请求（示例：/api/xxx）
        if path.startswith("/api/"):
            query_params = parse_qs(parsed_url.query)
            response_data = {
                "method": "GET",
                "path": path,
                "query_params": query_params,
                "message": "这是一个API响应"
            }
            self._set_response("application/json")
            self.wfile.write(json.dumps(response_data, ensure_ascii=False).encode("utf-8"))
            return
        
        # 静态文件请求
        else:
            # 如果请求根路径，默认返回 index.html
            if path == "/":
                file_path = os.path.join("", "index.html")
            else:
                # 构建文件路径（移除开头的斜杠）
                file_path = os.path.join("", path[1:])
            
            # 检查文件是否存在
            if os.path.exists(file_path) and os.path.isfile(file_path):
                try:
                    # 读取文件内容
                    with open(file_path, 'rb') as file:
                        content = file.read()               
                  
                    # 设置正确的 MIME 类型
                    mime_type = self._get_mime_type(file_path)
                    
                    # 替换文件内容
                    if path == "/":
                        json_dir = 'json/'
                        files = os.listdir(json_dir)
                        obj_arr = []
                        for file in files:
                            if file.endswith(".json"):
                                with open(json_dir+file, 'rb') as f:
                                    file_content = f.read()
                                    file_content_json = json.loads(file_content)
                                    obj = {
                                    'id':file_content_json.get('data').get('id'),
                                    'name':file_content_json.get('data').get('name')
                                    }
                                    obj_arr.append(obj)
                        result = ','.join([str(item) for item in obj_arr]) 
                        content = content.decode().replace('${list}',result).replace("'", "\"").encode()
                    self._set_response(mime_type)
                    self.wfile.write(content)
                except Exception as e:
                    traceback.print_exc()
                    self._set_response(status=500)
                    self.wfile.write(f"服务器错误: {str(e)}".encode("utf-8"))
            else:
                # 文件不存在，返回 404
                self._set_response(status=404)
                self.wfile.write("404 - 文件未找到".encode("utf-8"))
    
    # 处理 POST 请求
    def do_POST(self):
        content_length = int(self.headers["Content-Length"])
        post_data = self.rfile.read(content_length)
        
        data = {}
        
        try:
            # 尝试解析 JSON 格式数据
            data = json.loads(post_data)
        except json.JSONDecodeError:
            # 尝试解析表单格式数据
            data = parse_qs(post_data.decode("utf-8"))
        
        # 解析 URL
        parsed_url = urlparse(self.path)
        path = parsed_url.path
        
        # 解析 URL 和查询参数
        parsed_url = urlparse(self.path)
        query_params = parse_qs(parsed_url.query)
        
        
        # API 请求（示例：/api?id=1）
        if path.startswith("/api"):
            mode = data.get('mode')[0]
            
            self._set_response("application/json")
            if mode == 'get_item':
                try:
                    # 读取文件内容
                    print(data)
                    id = data.get('id')[0]  # 默认值为空字符串
                    print(id)
                    file_path = os.path.join("json",id+".json")
                    print(file_path)
                    with open(file_path, 'rb') as file:
                        content = file.read()
                    print(content)
                    response_data = content
                except Exception as e:
                    self._set_response(status=500)
                    self.wfile.write(f"服务器错误: {str(e)}".encode("utf-8"))
                self.wfile.write(response_data)
            elif mode == 'add_item':
            
                name = data.get('name')[0]
                body = data.get('body')[0]
                
                aid = str(int(time.time()))
                
                writeJSON = '{"state":"success","data":{"id":${id},"urlCode":null,"body":"${body}","name":"${name}"}}'
                writeJSON = writeJSON.replace('${id}',aid)
                writeJSON = writeJSON.replace('${name}',name)
                writeJSON = writeJSON.replace('${body}',body)
                
                with open('json/'+aid+'.json', 'w') as f:
                    f.writelines(writeJSON)
                
                returnJSON = '{"state":"success","data":{"id":'+aid+',"urlCode":null}}'
                self.wfile.write(returnJSON.replace("'", "\"").encode("utf-8"))
            else:
                self.wfile.write('{"state":"success","data":true}'.encode("utf-8"))
        else:
            # 非 API 请求返回错误
            self._set_response(status=400)
            self.wfile.write("错误的请求类型".encode("utf-8"))

if __name__ == "__main__":
    PORT = 8000
    server_address = ("", PORT)
    
    # 确保 public 目录存在
    public_dir = Path("public")
    public_dir.mkdir(exist_ok=True)
    
    httpd = ThreadingHTTPServer(server_address, CustomRequestHandler)
    print(f"服务器运行在端口 {PORT}")
    # print(f"静态文件目录: {os.path.abspath('public')}")
    print("访问 http://localhost:8000 查看网站")
    
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\n服务器关闭")
        httpd.server_close()